package com.ukao.steward.ui.menuLeft;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.tencent.bugly.beta.Beta;
import com.ukao.steward.R;
import com.ukao.steward.base.MvpActivity;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.listener.OnLocationListener;
import com.ukao.steward.pesenter.logistics.SettingPesenter;
import com.ukao.steward.util.ActivityUtils;
import com.ukao.steward.util.AppUtils;
import com.ukao.steward.util.CacheDataManager;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.LocationUtils;
import com.ukao.steward.util.T;
import com.ukao.steward.util.Utils;
import com.ukao.steward.view.logistics.SettingView;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import cn.jpush.android.api.JPushInterface;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;

/**
 * 设置
 */
public class SettingActivity extends MvpActivity<SettingPesenter> implements SettingView {


    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.location)
    TextView location;
    @BindView(R.id.switch2)
    SwitchCompat switch2;
    @BindView(R.id.txt_versions)
    TextView txtVersions;
    @BindView(R.id.txt_cache_size)
    TextView txtCacheSize;
    @BindView(R.id.clean_data_layout)
    RelativeLayout cleanDataLayout;
    @BindView(R.id.txt_quit)
    TextView txtQuit;
    @BindView(R.id.versions_layout)
    RelativeLayout versionsLayout;
    private LocationUtils mLocationUtils;
    private Handler mHandler = new Handler();
    private Subscription subscription;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_setting);
        ButterKnife.bind(this);
        initView();


    }

    @Override
    protected SettingPesenter createPresenter() {
        return new SettingPesenter(this);
    }


    @Override
    protected void initView() {

         if (CheckUtils.isMIUIDevices()){   versionsLayout.setVisibility(View.GONE);}
        mLocationUtils = new LocationUtils(this, mOnLocationListener);
        title.setText("设置");
        txtVersions.setText("V" + AppUtils.getVersionName(this));
        titleLayout.setBackgroundColor(resources.getColor(R.color.colorPrimary));
        try {

            txtCacheSize.setText(CacheDataManager.getTotalCacheSize(this));

        } catch (Exception e) {

            e.printStackTrace();

        }


    }


    @Override
    public void logoutSucceed() {
        JPushInterface.deleteAlias(Utils.getContext(), Constant.ALIAS_TAG);
        if (!isFinishing())
            loginAgain();

    }


    /**
     * 重新登录
     */
    private void loginAgain() {
        SaveParams.setLogin(false);
        ActivityUtils.JumpAgainActivity(this);
    }


    @OnClick({R.id.location, R.id.versions_layout, R.id.clean_data_layout, R.id.txt_quit, R.id.back_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.location:
                mLocationUtils.startLocation();
                break;
            case R.id.versions_layout:
                Beta.checkUpgrade();
                break;
            case R.id.clean_data_layout:
                if (!getText(txtCacheSize).equals("0MB")) {

                    new Thread(new clearCache()).start();
                }
                break;
            case R.id.txt_quit:
                mvpPresenter.logout();
                subscription = Observable.timer(2000, TimeUnit.MICROSECONDS)
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> logoutSucceed());

                break;
        }
    }


    @Override
    public void showError(String error) {

    }

    protected void unsubscribe() {
        if (subscription != null && !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unsubscribe();
        mLocationUtils.destroyLocation();
        mHandler.removeCallbacksAndMessages(null);

    }

    OnLocationListener mOnLocationListener = new OnLocationListener() {
        @Override
        public void OnLocationSucceed(AMapLocation amapLocation) {


            StringBuffer mStringBuffer = new StringBuffer();
            mStringBuffer.append(amapLocation.getAddress() + "\n" + "\n").append("经度 " + amapLocation.getLongitude())
                    .append(" 纬度 ").append(amapLocation.getLatitude());
            T.show(mStringBuffer.toString());
        }

        @Override
        public void OnLocationFailure(String error) {
            T.show(error);
        }
    };

    class clearCache implements Runnable {

        @Override

        public void run() {

            try {

                CacheDataManager.clearAllCache(SettingActivity.this);


                if (CacheDataManager.getTotalCacheSize(SettingActivity.this).startsWith("0")) {

                    handler.sendEmptyMessage(0);

                }

            } catch (Exception e) {

                return;

            }

        }

    }

    private Handler handler = new Handler() {

        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 0:
                    T.show("清理完成");

                    try {

                        txtCacheSize.setText(CacheDataManager.getTotalCacheSize(SettingActivity.this));

                    } catch (Exception e) {

                        e.printStackTrace();

                    }

            }

        }

        ;

    };


}
